#include <iostream>

#include "CSyncSignal.h"

using namespace std;

int main(int argc, char **argv)
{
	if(argc<2) {
		cerr << "Usage : " << argv[0] << " 1 or 2" << endl;
		cerr << "\t1\tfirst child 1, next child 2" << endl;
		cerr << "\t2\tfirst child 2, next child 1" << endl;
		exit(-1);
	}

	int first = atoi(argv[1]);

	pid_t pid1 = fork();
	if(pid1==0) { // 1st child
		CSyncSignal sync_signal;

		pid_t wpid = sync_signal.just_wait(SIGRTMIN);

		system("echo 'this is 1st child process'");

		sync_signal.just_send(wpid, SIGRTMIN+1);

		exit(0);
	}
	else {
		pid_t pid2 = fork();
		if(pid2==0) { // 2nd child
			CSyncSignal sync_signal;
			//sync_signal.wait_and_send(SIGRTMIN, SIGRTMIN+1);
			pid_t wpid = sync_signal.just_wait(SIGRTMIN);
			
			system("echo 'this is 2nd child process'");

			sync_signal.just_send(wpid, SIGRTMIN+1);

			exit(0);
		}
		else { // parent
			CSignalMask *child_signal = new CSignalMask();
			child_signal->add(SIGRTMIN+1);

			// blocking singal mask
			CSignal::instance()->block(child_signal);

			if(first==1) {
				CSyncSignal sync_signal;

				// pid1 first, pid2 next
				sync_signal.send_and_wait(pid1, SIGRTMIN, SIGRTMIN+1);
				sync_signal.send_and_wait(pid2, SIGRTMIN, SIGRTMIN+1);
			}
			else if(first==2) {
				CSyncSignal sync_signal;

				// pid2 first, pid1 next
				sync_signal.send_and_wait(pid2, SIGRTMIN, SIGRTMIN+1);
				sync_signal.send_and_wait(pid1, SIGRTMIN, SIGRTMIN+1);
			}
		}
	}
}
